<template>
  <div style="padding:20px">
    <!-- 头部组件 -->
    <PageTools>
      <template #left><span>总记录数: {{ total }} 条</span></template>
      <template #right>
        <el-button type="warning" size="mini" @click="$router.push('/import')">导入excel</el-button>
        <el-button type="danger" size="mini" @click="doExport">导出excel</el-button>
        <el-button type="primary" size="mini" @click="showDialog=true">新增员工</el-button>
      </template>
    </PageTools>
    <!-- 表格区域 -->
    <el-card>
      <el-table :data="list" border style="width: 100%">
        <el-table-column prop="date" label="序号" width="120" type="index" />
        <el-table-column sortable prop="username" label="姓名" width="120" />
        <el-table-column sortable prop="staffPhoto" label="头像" width="120">
          <template slot-scope="scope">
            <img :src="scope.row.staffPhoto" alt="" style="width:100%;">
          </template>
        </el-table-column>
        <el-table-column sortable prop="mobile" label="手机号" width="120" />
        <el-table-column sortable prop="workNumber" label="工号" width="120" />
        <el-table-column sortable label="聘用形式" width="120">
          <template slot-scope="scope">
            {{ formatEmployment(scope.row.formOfEmployment) }}
          </template>
        </el-table-column>
        <el-table-column sortable prop="departmentName" label="部门" width="120" />
        <el-table-column sortable prop="correctionTime" label="入职时间" width="120" />
        <el-table-column sortable prop="formOfEmployment" label="状态" width="120">
          <el-switch
            v-model="value"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="240">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="assignEmp(scope.row)">角色</el-button>
            <el-button type="text" size="small" @click="delEmp(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页组件 -->
    <el-row type="flex" justify="center" align="middle" style="height: 60px">
      <el-pagination
        layout="total, sizes,prev, pager, next, jumper"
        :total="total"
        @current-change="hCurrentChange"
        @size-change="hSizeChange"
      />
    </el-row>
    <!-- 新增组件Dialog -->
    <el-dialog title="新增员工" :visible.sync="showDialog">
      <EmpDia @close="showDialog=false" @success="success" />
    </el-dialog>
    <!-- 员工角色分配Dialog -->
    <el-dialog
      title="分配权限"
      :visible.sync="showDialogRole"
      :close-on-click-modal="false"
    >
      <AssignRole
        v-if="showDialogAssign"
        ref="assignRole"
        :employee-id="curEmployeId"
        @close="showDialogRole=false"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import EmpDia from './empDialog.vue'
import AssignRole from './assignRole.vue'
export default {
  name: '',
  components: { EmpDia, AssignRole },
  data() {
    return {
      value: true,
      list: [],
      page: 1,
      size: 10,
      total: 0,
      showDialog: false,
      tabelData: [],
      showDialogRole: false,
      curEmployeId: ''
    }
  },
  computed: {},
  created() {
    this.loadEmployeeList()
  },
  methods: {
    async loadEmployeeList() {
      const res = await getEmployeeList(this.page, this.size)
      console.log(res, '获取员工列表')
      this.list = res.data.rows
      this.total = res.data.total
    },
    formatEmployment(num) {
      // 从hireType中 通过id找到对应的元素的value
      const item = EmployeeEnum.hireType.find(item => item.id == num)
      if (item) {
        return item.value
      } else {
        return '非正式'
      }
    },
    hCurrentChange(curPage) {
      this.page = curPage
      this.loadEmployeeList()
    },
    hSizeChange(curSize) {
      this.size = curSize
      this.loadEmployeeList()
    },
    // 删除员工
    delEmp(id) {
      this.$confirm('确认删除吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployee(id)
        console.log(res, '删除员工')
        // 如果删除第最后一页的最一条数据之后，页面会显示不正常
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployeeList()
        this.$message.success(res.message)
      }).catch(e => e)
    },
    success() {
      this.showDialog = false
      // 添加成功，进入最后一页看数据
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.loadEmployeeList()
    },
    // 导出Excel
    async doExport() {
      const res = await getEmployeeList({ page: 1, size: this.total })
      console.log(res, '导出成功')
      import('@/vendor/Export2Excel').then(excel => {
        const list = res.data.rows
        const data = this.formatJson(list)
        excel.export_json_to_excel({
          header: this.tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    formatJson(jsonData) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      this.tHeader = Object.values(map)
      return jsonData.map((item) => {
        var newObj = {}
        var enKey = Object.keys(map)
        enKey.forEach(key => {
          newObj[map[key]] = item[key]
        })
        console.log(newObj, '导出员工列表')
        return Object.values(newObj)
      })
    },
    // 分配角色
    assignEmp({ id }) {
      console.log('角色id:', id)
      this.showDialogRole = true
      this.curEmployeId = id
      // 找到子组件，调用方法去获取最新的数据
      this.$nextTick(() => {
        this.$refs.assignRole.loadRoles()
      })
    }
  }
}
</script>
<style lang='less'  scoped>
</style>
